use git2::{Repository, StatusOptions};
use std::io::{self, Write};

fn test1() -> Result<(), std::io::Error> {
    let repo = match Repository::open(".") {
        Ok(r) => r,
        _ => std::process::exit(1),
    };
    let index = repo.index().unwrap();
    for entry in index.iter() {
        println!("{} - {}", std::str::from_utf8(&entry.path).unwrap(), entry.mtime.nanoseconds());
    }
    Ok(())
}

fn main() -> Result<(), std::io::Error> {
    let repo = match Repository::open(".") {
        Ok(r) => r,
        _ => std::process::exit(1),
    };
    let mut staged = false;
    let mut unstaged = false;
    let mut conflicted = false;
    let mut untracked = false;
    let mut branch = String::new();
    match repo.head() {
        Ok(head) => {
            match head.shorthand(){
                None => std::process::exit(1),
                Some(name) => branch.push_str(name),
            }
        },
        Err(_e) => std::process::exit(1),
    };
    let mut opts = StatusOptions::new();
    opts.include_untracked(true);
    let statuses = repo.statuses(Some(&mut opts)).unwrap();
    for entry in statuses.iter() {
        let status = entry.status();
        if status == git2::Status::INDEX_DELETED
            || status == git2::Status::INDEX_MODIFIED
            || status == git2::Status::INDEX_RENAMED
            || status == git2::Status::INDEX_TYPECHANGE
            || status == git2::Status::INDEX_NEW {
                staged = true;
            } else if status == git2::Status::WT_DELETED
            || status == git2::Status::WT_MODIFIED
            || status == git2::Status::WT_RENAMED
            || status == git2::Status::WT_TYPECHANGE {
                unstaged = true;
            } else  if status == git2::Status::WT_NEW {
                untracked = true;
            } else if status == git2::Status::CONFLICTED {
                conflicted = true;
            }
    }
    let reset = "\\[\\e[0m\\]";
    let green = "\\[\\e[32m\\]";
    let red = "\\[\\e[31m\\]";
    let mut stdout = io::stdout();
    write!(&mut stdout, " (").unwrap();
    write!(&mut stdout, "{}{}{}", green, branch, reset).unwrap();
    if unstaged || staged || untracked {
        write!(&mut stdout, " ")?;
    }
    if unstaged {
        write!(&mut stdout, "{}*{}", red, reset)?;
    }
    
    if staged {
        write!(&mut stdout, "{}+{}", green, reset)?;
    }
    if untracked {
        write!(&mut stdout, "{}..{}", red, reset)?;
    }
    if conflicted {
        write!(&mut stdout, "{} CONFLICT{}", red, reset)?;
    }
    write!(&mut stdout, ")")?;
    Ok(())
}

